const $ = layui.jquery;
const table = layui.table;
const form = layui.form;
const layer = layui.layer;
const laydate = layui.laydate;

$(() => {
    //渲染表格
    table.render({
        elem: '#tbl',
        url: ctx + "/sys/api/v1/order",
        method: "get",
        toolbar: '#tbl-tb',//表格工具栏
        defaultToolbar: ['filter', 'exports', 'print'],//表格工具栏右侧工具
        cellMinWidth: 80,//单位格最小宽度
        page: true,//是否开启分页
        limits: [10, 15, 30, 50, 100],//页面大小下拉
        limit: 10,//默认页面大小，此值必须在下拉框中存在，否则会报错
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'id', fixed: 'left', width: 80, title: 'ID', sort: true},
            {field: 'orderNo', width: 180, title: '订单号'},
            {
                field: 'memberId', width: 100, title: '会员账号', templet: function (d) {
                    if (d.member) {
                        return d.member.account;
                    } else {
                        return ""
                    }
                }
            },
            {field: 'totalPay', width: 120, title: '订单总额'},
            {field: 'payType', width: 120, title: '支付类型'},
            {field: 'state', width: 120, title: '状态'},
            {field: 'createdTime', width: 160, title: '下单时间'},
            {field: 'note', width: 160, title: '备注'},
            {field: 'receiverName', width: 160, title: '收货人'},
            {field: 'receiverPhone', width: 160, title: '收货人手机号'},
            {field: 'receiverAddrDetail', width: 260, title: '收货地址'},
            {fixed: 'right', title: '操作', width: 240, minWidth: 125, templet: '#rowBar'}
        ]]
    });

    //表格工具栏事件
    table.on("toolbar(tbl)", function (obj) {
        if (obj.event === "reset") {//重置
            $("#search-form")[0].reset();
        } else if (obj.event === "search") {//查询
            reload();
        } else if (obj.event === "del") {//批量删除
            let status = table.checkStatus("tbl");
            let checked = status.data;
            let ids = [];
            checked.forEach(it => ids.push(it.id));
            if (ids.length === 0) {
                layer.msg("请选中您要删除的行");
            } else {
                // 遍历选中行的数据
                let valid = true;
                checked.forEach(row => {
                    // 假设每行数据中有一个字段叫 `state`，表示状态
                    if (row.state === "已发货") {
                        layer.msg("存在已支付的订单，不能删除哦", {icon: 0});
                        valid = false;
                    } else if (row.state === "退款中") {
                        layer.msg("存在退款中的订单，不能删除哦", {icon: 0});
                        valid = false;
                    }
                });
                if (valid) {
                    layer.confirm("确定要删除选中的订单吗(请确保相应会员知情)", function (index) {
                        deleteByIds(ids);
                        layer.close(index);
                    });
                }
            }
        } else if (obj.event === "edit") {//修改订单
            let status = table.checkStatus("tbl");
            let checked = status.data;
            if (checked.length === 0) {
                layer.msg("请选中您要修改的订单");
            } else if (checked.length > 1) {
                layer.msg("您一次只能修改一个订单");
            } else {
                edit(checked[0]);
            }
        }
    });

    //行工具栏事件
    table.on("tool(tbl)", function (obj) {
        if (obj.event === "del") {//行删除
            let row = obj.data;//行数据
            layer.confirm("确定要删除选中的行吗?", function (index) {
                deleteByIds([row.id]);
                layer.close(index);
                reload();
            });
        } else if (obj.event === "edit") {//行修改
            edit(obj.data);
        } else if (obj.event === "ship") {//发货
            ship(obj);
        } else if (obj.event === "refunded") {//发货
            refunded(obj);
        }
    });

    laydate.render({
        elem: "[name=orderTime]",
        type: 'datetime',
        range: "~"
    });

});

//重载表格数据
function reload() {
    let formData = form.val("search-form");
    table.reload("tbl", {
        where: formData
    });
}

//批量删除订单
function deleteByIds(ids) {
    const url = ctx + "/sys/api/v1/order";
    $.ajax({
        url,
        method: "delete",
        dataType: "json",
        data: {
            ids
        },
        traditional: true,
        success(resp) {
            if (resp.success) {
                layer.msg(resp.msg || "删除成功，共删除" + resp.data + "条");
                reload();
            } else {
                layer.msg(resp.msg || "删除失败");
            }
        },
        error(resp) {
            let json = resp.responseJSON;
            layer.msg(json.msg || "删除失败");
        }
    });
}

function ship(obj) {
    if (obj.data.state !== "已支付") {
        layer.msg("只能对已支付的订单发货",{icon:0});
        return;
    }
    layer.confirm("是否确认发货?", function (index) {
        const url = ctx + "/sys/api/v1/order/ship";
        $.ajax({
            url,
            method: "patch",
            data: {
                id: obj.data.id
            },
            success(resp) {
                if (resp.success) {
                    layer.msg(resp.msg || "发货成功");
                    reload();
                } else {
                    layer.msg(resp.msg || "发货失败");
                }
                layer.close(index);
            }
        });
    });
}

function refunded(obj) {
    if (obj.data.state !== "退款中") {
        layer.msg("只能对退款中的订单退款");
        return;
    }
    layer.confirm("是否确认退款?", function (index) {
        const url = ctx + "/sys/api/v1/order/refunded";
        $.ajax({
            url,
            method: "patch",
            data: {
                id: obj.data.id
            },
            success(resp) {
                if (resp.success) {
                    layer.msg(resp.msg || "退款成功");
                    reload();
                } else {
                    layer.msg(resp.msg || "退款失败");
                }
                layer.close(index);
            }
        });
    });
}

//修改订单
function edit(row) {
    layer.open({
        type: 2, //弹出iframe窗口
        area: ['700px', '500px'],
        title: '修改订单',
        content: ctx + "/vm/sys/order/edit?id=" + row.id,
        btn: ["确定", "取消"],
        yes(index, $jqLayer) {
            const frameWin = $jqLayer.find("iframe")[0].contentWindow;
            frameWin.submitEdit(s => {
                if (s) {
                    layer.msg("修改品订单成功");
                    reload();
                    layer.close(index);
                } else {
                    layer.msg("修改订单失败");
                }
            })
        }
    });
}

